/**
 * Created by Administrator on 2017/3/3.
 */
var pool = require('./DBConnectPool');
var redis = require('redis');
var config = require('../../config');
var logger = require('../../common/Logger/Logger');
// var client = redis.createClient(6379, '127.0.0.1', {});
var redisTool = require('../../common/utils/redistools.js');
var async = require('async');
var OAuth = require('wechat-oauth');
var oauthDao = require('../dao/OauthDao');
var client = new OAuth(config.app.appid, config.app.appsecret, function (openid, callback) {
    // 传入一个根据openid获取对应的全局token的方法
    // 在getUser时会通过该方法来获取token
    oauthDao.getOauth(openid, function (message, result) {
        console.log('save access token to database success.');
        return callback(null, result);
    });
}, function (openid, token, callback) {
    // 请将token存储到全局，跨进程、跨机器级别的全局，比如写到数据库、redis等
    // 这样才能在cluster模式及多机情况下使用，以下为写入到文件的示例
    // 持久化时请注意，每个openid都对应一个唯一的token!
    oauthDao.setOauth(openid, token, function (message) {
        console.log('save access token to database success.');
        return callback(message);
    });
});

module.exports = {
    //插入手机号
    addUser: function (_param, callBack) {

        redisTool.setHset(_param, {
            phone: _param,
            createtime: 0,
            expiretime: 0,
            smscode: 0,
            username: ''
        }, function (err, result) {
            if (err) {
                console.log('Error: add phone to redis: ', err);
                callBack({
                    isSuccess: false
                });
                return;
            } else {
                callBack({
                    isSuccess: true,
                    rows: result
                })
            }
        });
    },
    // updateUser: function (_param, callBack) {
    //     // pool.getPoolConnection('mtsc', function (err, connection) {
    //     pool.getPoolConnection('sss', function (err, connection) {
    //         if (err) {
    //             console.log('Error: get connection from pool in register: ', err);
    //             return;
    //         }
    //         var sql = 'update register set createtime=?,expiretime=?,username=?,smscode=?,times=? where phone=? ';
    //         // var sql = 'insert into register (phone,createtime,expiretime,username) values(?,?,?,?) ';
    //         connection.query(sql, [_param], function (queryErr, rows) {
    //             if (queryErr) {
    //                 console.log('select * from cinema failed: ', err);
    //                 callBack({
    //                     isSuccess: false
    //                 });
    //             } else {
    //                 callBack({
    //                     isSuccess: true,
    //                     rows: rows
    //                 })
    //
    //             }
    //             connection.release();
    //         })
    //     })
    // },
    // //插入手机号，4字段
    // addPhone: function (_param, callBack) {
    //     // pool.getPoolConnection('mtsc', function (err, connection) {
    //     pool.getPoolConnection('sss', function (err, connection) {
    //         if (err) {
    //             console.log('Error: get connection from pool in register: ', err);
    //             return;
    //         }
    //         var sql = 'insert into register (phone,createtime,expiretime,username) values(?,?,?,?) ';
    //         connection.query(sql, [_param], function (queryErr, rows) {
    //             if (queryErr) {
    //                 console.log('select * from cinema failed: ', err);
    //                 callBack({
    //                     isSuccess: false
    //                 });
    //             } else {
    //
    //                 callBack({
    //                     isSuccess: true,
    //                     rows: rows
    //                 })
    //
    //             }
    //             connection.release();
    //         })
    //     })
    // },
    // 根据手机号查询结果
    selectByPhone: function (phone, callBack) {
        redisTool.getHgetall(phone, function (err, result) {
            if (err) {
                console.log('Error: get obj by phone to redis: ', err);
                callBack({
                    isSuccess: false
                });
                return;
            } else {
                callBack({
                    isSuccess: true,
                    rows: result
                })
            }
        });
    },
    // 将SMS码放入数据库,  根据手机号查询次数
    createSmsCode: function (code, phone, callBack) {
        var date = new Date();
        // date.to
        // var datetime=date.format("yyyy-mm-dd HH:MM:ss");
        var datetime = date.getTime();
        date.setMinutes(date.getMinutes() + 10);
        var endtime = date.getTime();
        redisTool.setHset(phone, {
            phone: phone,
            createtime: datetime,
            expiretime: endtime,
            smscode: code,
            username: ''
        }, function (err, result) {
            if (err) {
                console.log('Error: get obj by phone to redis: ', err);
                callBack({
                    isSuccess: false
                });
                return;
            } else {
                callBack({
                    isSuccess: true,
                    rows: result
                })
            }
        });
    },

    changePhone: function (_params, callBack) {
        pool.getPoolConnection('mtsc', function (err, connection) {
            const newphone = _params[1];
            const oldphone = _params[0];
            // const code=_params[2];
            const sql = 'select member_id from member_user where phone_number=?';
            if (err) {
                console.log('Error: get connection from pool in LogDao: ', err);
                return;
            }
            connection.query(sql, oldphone, function (queryErr, rows) {
                if (queryErr) {
                    console.log('select member_id from member_user: ', err);
                    callBack({
                        isSuccess: false
                    });
                } else {
                    if (!rows[0]) {
                        callBack({
                            isSuccess: false,
                            message: '查无手机'
                        });
                        return;
                    } else {
                        var oldId = rows[0].member_id;
                        //查询新手机号是否，注册过，是：提示手机已经注册；否：更新数据
                        connection.query('select member_id from member_user where phone_number=?', newphone, function (queryErr, rows) {
                            if (queryErr) {
                                console.log('select member_id from member_user: ', err);
                                callBack({
                                    isSuccess: false
                                });
                            } else {
                                if (!(rows.length > 0)) {
                                    // 可以更新
                                    //  var id=rows[0].member_id;
                                    var update = 'update member_user set phone_number=? where member_id=?';
                                    connection.query(update, [newphone, oldId], function (queryErr, rows) {
                                        if (queryErr) {
                                            console.log('select member_id from member_user: ', err);
                                            callBack({
                                                isSuccess: false,
                                                message: '手机号更新失败'
                                            });
                                        } else {
                                            callBack({
                                                isSuccess: true,
                                                message: '手机号更新成功',
                                                rows: rows
                                            })
                                        }
                                    })
                                } else {
                                    // 不可更换
                                    callBack({
                                        isSuccess: false,
                                        message: '手机号已经被注册'
                                    });

                                }
                            }
                            // connection.release();
                        });
                    }
                }
                connection.release();
            })
        })
    },

    getCardIdByUserId: function (_params, callBack) {

        // var tasks=[
        //     function (callback) {
        //         connection.query(sql, _params, function (queryErr, rows) {
        //                 console.log('111111111111111111111111111' + rows);
        //
        //                 if (queryErr) {
        //                     console.log('select member_id,phone_number from member_user  error: ', queryErr);
        //                     callBack({
        //                         isSuccess: false
        //                     });
        //                 } else {
        //                     callback(rows);
        //                 }
        //     }
        // ]



        var openid=_params;

        // console.log('111111111111111111111111111' + openid);
        pool.getPoolConnection('mtsc', function (err, connection) {
            var sql = "select member_id,phone_number from member_user where openid= ? ";
            if (err) {
                console.log('Error: get connection from pool in LogDao: ', err);
                return;
            }
            // console.log('111111111111111111111111111' + sql);

            connection.query(sql, openid, function (queryErr, rows) {
                // console.log('111111111111111111111111111  select' , JSON.stringify(rows));

                if (queryErr) {
                    console.log('select member_id,phone_number from member_user  error: ', queryErr);
                    callBack({
                        isSuccess: false
                    });
                } else {
                    if (!rows[0]) {
                        callBack({
                            isSuccess: false,
                            message: '查无此用户'
                        });
                        return;
                    } else {
                        var id = rows[0].member_id;
                        var phoneNumber=rows[0].phone_number;
                        var sqlcard = 'select card_id,start_time,end_time,cinema_name from member_card where member_id=?';
                        connection.query(sqlcard, id, function (queryErr, rows) {
                            if (queryErr) {
                                console.log('select member_id from member_user: ', queryErr);
                                callBack({
                                    isSuccess: false
                                });
                            } else {
                                //多张会员卡的情况
                                if (rows && rows.length > 0) {
                                    callBack({
                                        isSuccess: true,
                                        cardid: rows,
                                        phone:phoneNumber
                                    })
                                } else {
                                    callBack({
                                        isSuccess: false,
                                        message: '查无会员卡',
                                        phone:phoneNumber
                                    })
                                }

                            }
                        })
                    }
                }
                connection.release();
            });
        })
    },

    /**
     *
     * @param openid
     * @param callBack
     */
    userLogin: function (openid, phone, callBack) {
        pool.getPoolConnection('mtsc', function (err, connection) {
            var sql = 'update member_user set openid=? where phone_number = ? ';
            if (err) {
                console.log('Error: get connection from pool in LogDao: ', err);
                return;
            }
            connection.query(sql, [openid, phone], function (queryErr, rows) {
                if (queryErr) {
                    console.log('select member_id from member_user: ', queryErr);
                    callBack({
                        isSuccess: false
                    });
                } else {
                    if (rows && rows.affectedRows == 1) {
                        var textMsg = '恭喜您登录成功。';
                        api.sendText(openid,textMsg ,function (err, result) {
                            if (err) {
                                //res.send({error: '1',message: 'fail'});
                                // res.send({error: '0',message: 'success'});
                                logger.info(err);
                            } else {
                                // res.send({error: '0',message: 'success'});
                            }
                        });
                        callBack({
                            isSuccess: true,
                            message: '登录成功'
                        });
                        return;
                    } else {
                        callBack({
                            isSuccess: false,
                            message: '查无手机'
                        });
                    }
                }
                connection.release();
            });
            //  var j=1;
        })
    },
    findUserByOpenId: function (id, callBack) {
        pool.getPoolConnection('mtsc', function (err, connection) {
            var sql = 'select * from member_user where openid = ? ';
            if (err) {
                console.log('Error: get connection from pool in LogDao: ', err);
                return;
            }
            connection.query(sql, id, function (queryErr, rows) {
                if (queryErr) {
                    console.log('select member_id from member_user: ', queryErr);
                    callBack({
                        isSuccess: false
                    });
                } else {
                    if (!rows[0]) {

                        callBack({
                            isSuccess: false,
                            message: '查无手机'
                        });
                        return;
                    } else {
                        callBack(rows[0]);
                    }
                }
                connection.release();
            });
            //  var j=1;
        })
    },

    // changeUser:function()
    changeUser: function (_param, callBack) {
        var openid = _param[0];
        var phone = _param[1];
        var user = _param[2];
        //要添加事务

        // 旧号openid清零
        pool.getPoolConnection('mtsc', function (err, connection) {
            if (err) {
                console.log('Error: get connection from pool in member: ', err);
                return;
            }
            // 添加事务处理
            connection.beginTransaction(function (err) {
                if (err) {
                    throw err;
                }
                var selectPhone = "select phone_number from member_user where openid=?";
                connection.query(selectPhone, openid, function (queryErr, rows) {
                    if (queryErr) {
                        console.log('select phone_number failed: ', queryErr);
                        callBack({
                            isSuccess: false
                        });
                        return connection.rollback(function () {
                            throw error;
                        });
                    } else {
                        if (rows && rows[0]) {
                            if (rows[0].phone_number == phone) {
                                callBack({
                                    isSuccess: false,
                                    message: '请重新输入手机号'
                                })
                            } else {
                                //不相等，openid清零；新手机号添加，如果
                                var sql = "UPDATE member_user set openid='' WHERE openid=? ";
                                connection.query(sql, openid, function (queryErr, rows) {
                                    if (queryErr) {
                                        console.log('select member_user failed: ', queryErr);
                                        callBack({
                                            isSuccess: false
                                        });
                                        return connection.rollback(function () {
                                            throw error;
                                        });
                                    } else {


                                        var sqlNewPhone = "select * from member_user where phone_number=?";
                                        connection.query(sqlNewPhone, phone, function (queryErr, rows) {
                                            if (queryErr) {
                                                console.log('iselect * from member_user where phone_number failed: ', queryErr);
                                                callBack({
                                                    isSuccess: false
                                                });
                                                return connection.rollback(function () {
                                                    throw error;
                                                });
                                            } else {
                                                // 有账号，更换openid，无账号新建
                                                if (rows[0]) {
                                                    var member_id = rows[0].member_id;
                                                    var updateuser = "update member_user set openid=? where member_id=?";
                                                    connection.query(updateuser, [openid, member_id], function (queryErr, rows) {
                                                        if (queryErr) {
                                                            console.log('update into member_user failed: ', queryErr);
                                                            callBack({
                                                                isSuccess: false
                                                            });
                                                            return connection.rollback(function () {
                                                                throw error;
                                                            });
                                                        } else {
                                                            connection.commit(function (err) {
                                                                if (err) {
                                                                    return connection.rollback(function () {
                                                                        throw err;
                                                                    });
                                                                }
                                                                callBack({
                                                                    isSuccess: true,
                                                                    message:'old',
                                                                    rows: rows
                                                                });
                                                                console.log('success!');
                                                            });

                                                        }
                                                    })
                                                } else {
                                                    // 新建账号
                                                    client.getUser(openid, function (err, result) {
                                                        if (err) {
                                                            callBack({
                                                                status: 'error',
                                                                message: '网页过期，请刷新页面'
                                                            });
                                                            return
                                                        }
                                                        var userInfoNew = result;

                                                        // console.log(userInfo);
                                                        var param = [openid, userInfoNew.nickname, userInfoNew.sex, phone, userInfoNew.province, userInfoNew.city, userInfoNew.country, userInfoNew.headimgurl, userInfoNew.privilege.toString()];
                                                        console.log(param);
                                                        // var param = [openid, userInfoNew.nickname, userInfoNew.sex, userInfoNew.phone_number, userInfoNew.province, userInfoNew.city, userInfoNew.country, userInfoNew.headimgurl, userInfoNew.privilege.toString()];
                                                        var sql = 'insert into member_user (openid,nickname,sex,phone_number,province,city,country,headimgurl,privilege) values(?,?,?,?,?,?,?,?,?)';
                                                        console.log(param);
                                                        console.log(sql);
                                                        connection.query(sql, param, function (queryErr, rows) {
                                                            if (queryErr) {
                                                                console.log('insert into member_user failed: ', queryErr);
                                                                callBack({
                                                                    isSuccess: false
                                                                });
                                                                return connection.rollback(function () {
                                                                    throw error;
                                                                });
                                                            } else {
                                                                connection.commit(function (err) {
                                                                    if (err) {
                                                                        return connection.rollback(function () {
                                                                            throw err;
                                                                        });
                                                                    }

                                                                    callBack({
                                                                        isSuccess: true,
                                                                        message:'new',
                                                                        rows: rows
                                                                    });
                                                                    console.log('success!');
                                                                });
                                                            }
                                                        })

                                                    });
                                                }
                                            }
                                        })
                                    }
                                })
                            }
                        }
                    }
                    connection.release();
                })


            })


        })
    },
    clearOpenidByOpenId: function (_param, callBack) {
        // var phone
        pool.getPoolConnection('mtsc', function (err, connection) {
            if (err) {
                console.log('Error: get connection from pool in member: ', err);
                return;
            }
            var sql = "UPDATE member_user set openid='' WHERE openid=? ";
            connection.query(sql, [_param], function (queryErr, rows) {
                if (queryErr) {
                    console.log('select member_user failed: ', queryErr);
                    callBack({
                        isSuccess: false
                    });
                } else {
                    callBack({
                        isSuccess: true,
                        rows: rows
                    })

                }
                connection.release();
            })
        })
    },

    /**
     * 如果没有openid，手机号，新建用户；
     * 没有openid有手机号，更新
     * @param openid
     * @param phone
     * @param userInfo
     * @param callBack
     */
    addAndLogin: function (openid, phone, user, callBack) {

        // console.log('111111111111111111111111111111111111111111 enter ');
        pool.getPoolConnection('mtsc', function (err, connection) {
            if (err) {
                console.log('Error: get connection from pool in member: ', err);
                return;
            }
            // console.log('111111111111111111111111111111111111111111 ');
            connection.query('select phone_number from member_user where openid=?', openid, function (queryErr, rows) {
                if (queryErr) {
                    console.log('select member_user failed: ', queryErr);
                    callBack({
                        isSuccess: false
                    });
                } else {
                    // console.log('111111111111111111111111111111111111111111 ses ');
                    if (rows && rows.length > 0) {
                        //登录
                        var sqlphone = rows[0].phone_number;
                        if (phone == sqlphone) {
                            console.log('1111111111111111111111111111111登录成功')
                            callBack({
                                isSuccess: true
                            })
                        } else {
                            // 查询手机号是否存在
                            connection.query('select * from member_user where phone_number=?', phone, function (queryErr, rows) {
                                if (queryErr) {
                                    console.log('insert into member_user failed: ', queryErr);
                                    callBack({
                                        isSuccess: false
                                    });
                                } else {
                                    if (rows && rows.length > 0) {
                                        // var phoneNumber = rows[0].phone_number;
                                        // 更新
                                        connection.query('update member_user set openid=? where phone_number=?', [openid, phone], function (queryErr, rows) {
                                            if (queryErr) {
                                                console.log('insert into member_user failed: ', queryErr);
                                                callBack({
                                                    isSuccess: false
                                                });
                                            } else {
                                                if (rows && rows.affectedRows > 0) {
                                                    callBack({
                                                        isSuccess: true
                                                    })
                                                } else {
                                                    callBack({
                                                        isSuccess: false
                                                    });
                                                }
                                            }
                                        })
                                    } else {
                                        // 新手机号，注册
                                        var param = [user.openid, user.nickname, user.sex, user.phone_number, user.province, user.city, user.country, user.headimgurl, user.privilege.toString()];
                                        var sql = 'insert into member_user (openid,nickname,sex,phone_number,province,city,country,headimgurl,privilege) values(?,?,?,?,?,?,?,?,?)';
                                        connection.query(sql, [param], function (queryErr, rows) {
                                            if (queryErr) {
                                                console.log('insert into member_user failed: ', queryErr);
                                                callBack({
                                                    isSuccess: false
                                                });
                                            } else {
                                                if (rows && rows.affectedRows > 0) {
                                                    callBack({
                                                        isSuccess: true
                                                    })
                                                } else {
                                                    callBack({
                                                        isSuccess: false
                                                    });
                                                }
                                            }
                                        })
                                    }
                                }

                            })
                        }
                    } else {
                        // 没有openid
                        // 查询手机号是否存在
                        // console.log('111111111111111111111111111111111111111111  no open');
                        connection.query('select * from member_user where phone_number=?', phone, function (queryErr, rows) {
                            if (queryErr) {
                                // console.log('111111111111111111111111111111111111111111  no open s p'+queryErr.toString());

                                console.log('select phone member_user failed: ', queryErr);
                                callBack({
                                    isSuccess: false
                                });
                            } else {
                                // console.log('111111111111111111111111111111111111111111 ');

                                if (rows && rows.length > 0) {
                                    // var phoneNumber = rows[0].phone_number;
                                    // 更新
                                    connection.query('update member_user set openid=? where phone_number=?', [openid, phone], function (queryErr, rows) {
                                        if (queryErr) {
                                            console.log('update member_user failed: ', queryErr);
                                            callBack({
                                                isSuccess: false
                                            });
                                        } else {
                                            if (rows && rows.affectedRows > 0) {
                                                // console.log('1111111111111111111111111111111更新手机openid成功')

                                                callBack({
                                                    isSuccess: true
                                                })
                                                connection.release();
                                            } else {
                                                callBack({
                                                    isSuccess: false
                                                });
                                                connection.release();
                                            }
                                        }
                                    })
                                } else {
                                    // 新手机号，注册
                                    // console.log('111111111111111111111111111111111111111111  insert ');

                                    var param = [user.openid, user.nickname, user.sex, user.phone_number, user.province, user.city, user.country, user.headimgurl, user.privilege.toString()];
                                    var sql = 'insert into member_user (openid,nickname,sex,phone_number,province,city,country,headimgurl,privilege) values(?,?,?,?,?,?,?,?,?)';
                                    connection.query(sql, param, function (queryErr, rows) {
                                        if (queryErr) {
                                            console.log('insert into member_user failed: ', queryErr);
                                            callBack({
                                                isSuccess: false
                                            });
                                            connection.release();
                                        } else {
                                            if (rows && rows.affectedRows > 0) {
                                                callBack({
                                                    isSuccess: true
                                                })
                                            } else {
                                                // console.log("1111111111111111111111111111111111111111111 insert")
                                                callBack({
                                                    isSuccess: false
                                                });
                                            }
                                            connection.release();
                                        }
                                    })
                                }
                            }

                        })
                    }
                }

            })


        })
    }
}





